package qc.gateway.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.gateway.entity.QcApiFilters;
import qc.gateway.repository.QcApiFilterRepository;

import java.util.List;

/**
 * QcApiFilterService
 *
 * @author QuCheng Tech
 * @since 2023/11/7
 */
@Service
public class QcApiFilterService {
    private QcApiFilterRepository repository;

    @Autowired
    public void setQcApiFilterRepository(QcApiFilterRepository repository) {
        this.repository = repository;
    }

    /***
     * 查询系统中所有有效状态的过滤规则，按写入时间降序排序
     *
     * @return java.util.List<qc.gateway.entity.QcApiFilters>
     * @author QuCheng Tech
     * @since 2023/11/7
     */
    public List<QcApiFilters> getAllValidFilters() {
        LambdaQueryWrapper<QcApiFilters> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QcApiFilters::getFlag, ResourceStatusFlagEnum.NORMAL);
        wrapper.orderByDesc(QcApiFilters::getUpdatetm);

        return repository.selectList(wrapper);
    }

    /***
     * 将指定ID的过滤规则命中次数加1
     *
     * @param id 过滤规则ID
     * @return void
     * @author QuCheng Tech
     * @since 2023/11/7
     */
    public void addHitCounts(String id) {
        LambdaUpdateWrapper<QcApiFilters> wrapper = new LambdaUpdateWrapper<>();
        wrapper.setSql("`COUNT`=`COUNT`+1");
        wrapper.eq(QcApiFilters::getId, id);

        repository.update(null, wrapper);
    }
}
